package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Service {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("110.41.84.205");
        factory.setPort(5672); // 端口号
        factory.setUsername("study"); // 账号
        factory.setPassword("study"); // 密码
        factory.setVirtualHost("Demo"); // 虚拟主机

        Connection connection = factory.newConnection();// 建立连接
        // 建立通道
        Channel channel = connection.createChannel();

        // 生明队列
        channel.queueDeclare(Constants.RPC_QUEUE_RPC,true, false, false,  null);
        channel.basicQos(1); // 生明队列最多收到一条消息
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // 处理消息
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties().builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                String response = "处理消息： " + new String(body) + "处理成功";
                System.out.println(response);
                channel.basicPublish("" , properties.getReplyTo(), replyProps, response.getBytes());
                // 对消息进行应答
                channel.basicAck(envelope.getDeliveryTag(),false);

            }
        };
        channel.basicConsume(Constants.RPC_QUEUE_RPC,consumer);
    }
}
